package com.info.zhiduoduo.core.service.impl;

import com.info.zhiduoduo.common.configs.MailConfig;
import com.info.zhiduoduo.core.service.MailService;

import org.simplejavamail.api.email.AttachmentResource;
import org.simplejavamail.api.email.Email;
import org.simplejavamail.api.email.EmailPopulatingBuilder;
import org.simplejavamail.api.mailer.Mailer;
import org.simplejavamail.api.mailer.config.TransportStrategy;
import org.simplejavamail.email.EmailBuilder;
import org.simplejavamail.mailer.MailerBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

import javax.activation.FileDataSource;
import javax.annotation.PostConstruct;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class MailServiceImpl implements MailService {

	@Autowired
	MailConfig mailConfig;

	private Mailer mailer;

	@PostConstruct
	private void init() {
		mailer = MailerBuilder.withSMTPServer(mailConfig.getHost(), mailConfig.getPort(), mailConfig.getUsername(), mailConfig.getPassword())
				.withTransportStrategy(TransportStrategy.SMTP)
				.withSessionTimeout(10 * 1000)
				.clearEmailAddressCriteria() // turns off email validation
				.withDebugLogging(true)
				// .async()
				.buildMailer();
	}

	@Override
	public boolean sendMailWithAttachments(List<String> toList, String subject, String content, List<String> attachments) {
		if (CollectionUtils.isEmpty(toList)) return false;

		try {
			EmailPopulatingBuilder builder = EmailBuilder.startingBlank().from("塾人创客平台", mailConfig.getUsername()).to(null, toList)
					// .to("C. Cane", "candycane@candyshop.org")
					// .ccWithFixedName("C. Bo group", "chocobo1@candyshop.org", "chocobo2@candyshop.org")
					// .bcc("Mr Sweetnose <snose@candyshop.org>")
					// .withReplyTo("lollypop", "lolly.pop@othermail.com")
					.withSubject(subject)
					// .withHTMLText("<img src='cid:wink1'><b>We should meet up!</b><img src='cid:wink2'>")
					.withPlainText(content);// .withCalendar(CalendarMethod.REQUEST, iCalendarText)
			// .withEmbeddedImage("wink1", imageByteArray, "image/png")
			// .withEmbeddedImage("wink2", imageDatesource)
			// .withAttachment("invitation", pdfByteArray, "application/pdf")
			// .withAttachment("dresscode", odfDatasource)
			// .withHeader("X-Priority", 5)
			// .withReturnReceiptTo()
			// .withDispositionNotificationTo("notify-read-emails@candyshop.com")
			// .withBounceTo("tech@candyshop.com")
			// .signWithDomainKey(privateKeyData, "somemail.com", "selector") // DKIM
			// .signWithSmime(pkcs12Config)
			// .encryptWithSmime(x509Certificate)

			if (!CollectionUtils.isEmpty(attachments)) {
				List<AttachmentResource> list = attachments.stream().map(FileDataSource::new).map(ds -> new AttachmentResource(null, ds)).collect(Collectors.toList());
				builder.withAttachments(list);
			}

			Email email = builder.buildEmail();
			mailer.sendMail(email);
			return true;

		} catch (Exception e) {
			log.error("发送邮件失败：{}, 报错信息：", subject, e);
		}
		return false;
	}
}
